import React, { Component } from 'react';
import styles from './index.module.scss';
import classNames from 'classnames';
import { update } from '@/utils/immutableUtil';

class Comp extends Component {
  iframeRef = React.createRef();
  state = {
    iframeKey: '',
    selectedElement: null,
    textContent: '',
  };

  // 标准缩放计算 - 以宽度为基准
  calculateScale = () => {
    const { data, containerWidth } = this.props;

    // iframe 原始尺寸
    const targetWidth = data.width;
    const targetHeight = data.height;
    // 宽高比
    const aspectRatio = targetWidth / targetHeight;

    // 根据宽高比计算容器高度
    const containerHeight = containerWidth / aspectRatio;

    // 计算缩放值
    const scale = containerWidth / targetWidth;

    return {
      scale,
      containerHeight: containerHeight,
      containerWidth: containerWidth
    };
  };
  
  // 全屏模式下的缩放计算 - 根据屏幕高度限制自动调整
  calculateScale2 = () => {
    const { data, containerWidth, containerHeight } = this.props;

    // iframe 原始尺寸
    const targetWidth = data.width;
    const targetHeight = data.height;
    // 宽高比
    const aspectRatio = targetWidth / targetHeight;

    // 获取视口尺寸
    const viewportWidth = containerWidth || window.innerWidth;
    const viewportHeight = containerHeight || window.innerHeight;

    // 计算缩放值和容器尺寸
    let scale, finalWidth, finalHeight;

    // 如果视口的宽高比大于幻灯片的宽高比，说明高度是限制因素
    // 此时应该以高度为基准计算宽度
    if (viewportWidth / viewportHeight > aspectRatio) {
      // 高度是限制因素，以高度为基准
      finalHeight = viewportHeight;
      finalWidth = finalHeight * aspectRatio;
      scale = finalHeight / targetHeight;
    } else {
      // 宽度是限制因素，以宽度为基准
      finalWidth = viewportWidth;
      finalHeight = finalWidth / aspectRatio;
      scale = finalWidth / targetWidth;
    }

    return {
      scale,
      containerHeight: finalHeight,
      containerWidth: finalWidth
    };
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  
  render() {
    const { data, isFullscreen } = this.props;
    
    // 根据是否全屏选择不同的缩放计算方法
    const scaleInfo = isFullscreen ? this.calculateScale2() : this.calculateScale();
    const { scale, containerHeight, containerWidth } = scaleInfo;

    return (
      <div
        className={styles.fragment}
        style={{
          height: containerHeight,
          width: containerWidth ? `${containerWidth}px` : '100%',
          position: 'relative',
          margin: '0 auto', // 居中显示
          overflow: 'hidden'
        }}
      >
        <iframe
          src={data.url}
          srcDoc={data.code}
          style={{
            transform: `scale(${scale})`,
            transformOrigin: '0 0',
            width: `${data.width}px`,
            height: `${data.height}px`,
            border: 'none',
            position: 'absolute',
          }}
          sandbox="allow-same-origin allow-scripts"
        />
      </div>
    );
  }
}

export default Comp;
